package repository

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"go-fox-edge-kernel-manager/component"
	"time"
)

type repoLocalJarFileConfigService struct {
}

func (e *repoLocalJarFileConfigService) getConfigValue() (map[string]interface{}, error) {
	return component.ManageConfigService.GetConfigValue("device-service", "system", "decoderConfig")
}

func (e *repoLocalJarFileConfigService) saveConfigValue(configValue map[string]interface{}) error {
	return component.ManageConfigService.SaveConfigValue("device-service", "system", "decoderConfig", configValue)
}

func (e *repoLocalJarFileConfigService) GetLoads() ([]string, error) {
	configValue, err := e.getConfigValue()
	if err != nil {
		return nil, err
	}

	result := make([]string, 0)
	dataList := Map.GetOrDefault(configValue, "list", make([]interface{}, 0))
	for _, val := range dataList.([]interface{}) {
		data := val.(map[string]interface{})

		fileName := data["fileName"]
		if Method.HasEmpty(fileName) {
			continue
		}

		load := data["load"]
		if true != load {
			continue
		}

		result = append(result, fileName.(string))

	}

	return result, nil
}

func (e *repoLocalJarFileConfigService) UpdateConfig(fileName string, load bool) error {
	configValue, err := e.getConfigValue()
	if err != nil {
		return err
	}

	//result := make([]string, 0)
	dataList := Map.GetOrDefault(configValue, "list", make([]interface{}, 0))

	// 修改数值
	dataList, err = e.setConfigValue(fileName, load, dataList.([]interface{}))
	if err != nil {
		return err
	}
	configValue["list"] = dataList

	// 保存数据
	e.saveConfigValue(configValue)

	return nil
}

func (e *repoLocalJarFileConfigService) setConfigValue(fileName string, load bool, dataList []interface{}) ([]interface{}, error) {
	for _, v := range dataList {
		entity := v.(map[string]interface{})

		fileNameValue := entity["fileName"]
		if fileNameValue == "" {
			continue
		}

		if fileNameValue == fileName {
			time := time.Now().UnixMilli()
			entity["fileName"] = fileName
			entity["load"] = load
			entity["createTime"] = time
			entity["updateTime"] = time
			return dataList, nil
		}
	}

	time := time.Now().UnixMilli()
	entity := make(map[string]interface{})
	entity["fileName"] = fileName
	entity["load"] = load
	entity["createTime"] = time
	entity["updateTime"] = time

	dataList = append(dataList, entity)

	return dataList, nil
}
